package dongze.com.ckdj.fragment;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.preference.ListPreference;
import android.preference.Preference;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.google.gson.Gson;

import java.util.List;

import javax.inject.Inject;

import dongze.com.ckdj.CKDJApplication;
import dongze.com.ckdj.R;
import dongze.com.ckdj.activity.CheckInActivity;
import dongze.com.ckdj.dagger.DataStore;
import dongze.com.ckdj.dagger.component.AppComponent;
import dongze.com.ckdj.dagger.component.DaggerSectionComponent;
import dongze.com.ckdj.dagger.component.SectionComponent;
import dongze.com.ckdj.dagger.component.UserComponent;
import dongze.com.ckdj.dagger.module.SectionModule;
import dongze.com.ckdj.data.entity.response.BrandResponse;
import dongze.com.ckdj.data.entity.response.InspectionSectionResponse;
import dongze.com.ckdj.map.MapUtil;
import dongze.com.ckdj.util.MyLog;
import io.reactivex.observers.DisposableObserver;


/**
 * Created by fanqwz on 2017/8/10.
 */

public class UserConfigurationFragment extends ProcessablePreferenceFragment implements Preference.OnPreferenceChangeListener {
    private static final String TAG = UserConfigurationFragment.class.getSimpleName();
    ListPreference brandPreference;
    ListPreference sectionPreference;
    List<BrandResponse> brandResponses;
    List<InspectionSectionResponse> inspectionSectionResponses;
    MapUtil mapUtil;
    Handler handler;

    @Inject
    DataStore dataStore;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        MyLog.d(TAG, "onCreate: ");
        super.onCreate(savedInstanceState);
        handler = new Handler(Looper.getMainLooper());
        addPreferencesFromResource(R.xml.user_preference);
        AppComponent appComponent = ((CKDJApplication) getActivity().getApplication()).getComponent(AppComponent.class);
        mapUtil = new MapUtil(appComponent);
        appComponent.inject(this);
        init();
    }

    @Override
    public void onDestroy() {
        mapUtil.dispose();
        super.onDestroy();
    }

    private void init() {
        MyLog.d(TAG, "init: ");
        mapUtil.getBrands("1", new DisposableObserver<List<BrandResponse>>() {
            @Override
            protected void onStart() {
                super.onStart();
                doProcessing();
            }

            @Override
            public void onNext(List<BrandResponse> value) {
                initPreference();
                brandPreference.setEnabled(true);

                brandResponses = value;
                CharSequence[] entries = new CharSequence[brandResponses.size()];
                CharSequence[] entryvalues = new CharSequence[brandResponses.size()];

                for (int i = 0; i < brandResponses.size(); i++) {
                    entries[i] = brandResponses.get(i).getBrand_name();
                    entryvalues[i] = brandResponses.get(i).getBrand_code();
                }
                brandPreference.setEntryValues(entryvalues);
                brandPreference.setEntries(entries);
            }

            @Override
            public void onError(Throwable e) {
                MyLog.e(TAG, "onError: ", e);
                brandErr();
                finishProcessing();
            }

            @Override
            public void onComplete() {
                finishProcessing();
            }
        });
    }

    private void initPreference() {
        brandPreference = (ListPreference) findPreference("pref_brand_name");
        sectionPreference = (ListPreference) findPreference("pref_inspection_section");
        brandPreference.setOnPreferenceChangeListener(this);
        brandPreference.setSummary(brandPreference.getEntry());
        sectionPreference.setOnPreferenceChangeListener(this);
        sectionPreference.setSummary(sectionPreference.getEntry());
    }

    private void getInspectionSection(String brand) {
        mapUtil.getInspectionSections(brand, new DisposableObserver<List<InspectionSectionResponse>>() {
            @Override
            protected void onStart() {
                super.onStart();
                doProcessing();
            }

            @Override
            public void onNext(List<InspectionSectionResponse> value) {
                inspectionSectionResponses = value;
                sectionPreference.setEnabled(true);

                CharSequence[] entries = new CharSequence[value.size()];
                CharSequence[] entryvalues = new CharSequence[value.size()];

                for (int i = 0; i < value.size(); i++) {
                    entries[i] = value.get(i).getNode_name();
                    entryvalues[i] = value.get(i).getNode_code();
                }

                sectionPreference.setEntries(entries);
                sectionPreference.setEntryValues(entryvalues);
            }

            @Override
            public void onError(Throwable e) {
                MyLog.e(TAG, "onError: ", e);
                sectionErr();
                finishProcessing();
            }

            @Override
            public void onComplete() {
                finishProcessing();
            }
        });
    }

    private void brandErr() {
        if (getActivity() != null)
            new AlertDialog.Builder(getActivity())
                    .setTitle("错误")
                    .setMessage("没有查询到品牌")
                    .create()
                    .show();
        else
            MyLog.e(TAG, "brandErr: 没有查询到品牌");
    }

    private void sectionErr() {
        new AlertDialog.Builder(getActivity())
                .setTitle("错误")
                .setMessage("没有查询到环节")
                .create()
                .show();
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        MyLog.d(TAG, "onPreferenceChange: " + preference + "," + newValue);

        if (preference == brandPreference) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    brandPreference.setSummary(brandPreference.getEntry());
                }
            });

            getInspectionSection(String.valueOf(newValue));
        } else if (preference == sectionPreference) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    sectionPreference.setSummary(sectionPreference.getEntry());
                }
            });

            CKDJApplication application = (CKDJApplication) getActivity().getApplicationContext();
            BrandResponse brand = null;
            for (BrandResponse b :
                    brandResponses) {
                if (TextUtils.equals(b.getBrand_code(), brandPreference.getValue())) {
                    brand = b;
                    break;
                }
            }

            InspectionSectionResponse inspectionSection = null;
            for (InspectionSectionResponse i :
                    inspectionSectionResponses) {
                if (TextUtils.equals(i.getNode_code(), String.valueOf(newValue))) {
                    inspectionSection = i;
                    break;
                }
            }

            if (brand != null && inspectionSection != null && application.getComponent(UserComponent.class) != null) {
                dataStore.set(BrandResponse.class, brand);
                dataStore.set(InspectionSectionResponse.class, inspectionSection);
                MyLog.d(TAG,new Gson().toJson(brand));
                MyLog.d(TAG,new Gson().toJson(inspectionSection));
                SectionComponent sectionComponent = DaggerSectionComponent.builder()
                        .sectionModule(new SectionModule(brand, inspectionSection))
                        .userComponent(application.getComponent(UserComponent.class))
                        .build();
                application.addComponent(SectionComponent.class, sectionComponent);
                startActivity(new Intent(getActivity().getApplicationContext(), CheckInActivity.class));

            }
        }

        return true;
    }
}
